package com.luyue.zagj.activity.myAccount;

import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.luyue.zagj.BaseActivity;
import com.luyue.zagj.R;
import com.luyue.zagj.activity.home.ApplyLabelActivity;
import com.luyue.zagj.domin.PeopleInfomation;
import com.luyue.zagj.utils.OtherUtils;
import com.luyue.zagj.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Chen qin lang on 2016/12/13.
 * 邮箱 :   619766577@qq.com
 */
public class CarInfoActivity extends BaseActivity {

    @Bind(R.id.select_iv_idcardposition)
    ImageView selectIvIdcardposition;
    @Bind(R.id.select_arrmedphoto)
    ImageView selectArrmedphoto;
    @Bind(R.id.select_iv_idcardback)
    ImageView selectIvIdcardback;
    @Bind(R.id.home_call_police)
    ImageView homeCallPolice;
    @Bind(R.id.select_iv_carinfo)
    ImageView selectIvCarinfo;
    @Bind(R.id.home_insurance)
    ImageView homeInsurance;
    @Bind(R.id.carinfo_bottom)
    Button button;
    @Bind(R.id.ll_select_pictrue)
    LinearLayout llSelectPictrue;
    @Bind(R.id.iv_show_pictrue)
    ImageView ivShowPictrue;
    @Bind(R.id.ll_show_pictrue)
    LinearLayout llShowPictrue;
    private ArrayList<File> images;
    private static final int REQUEST_CAMERA = 1;
    private static final int REQUEST_ALBUM_OK = 2;
    private static final String TAG = "123";

    private File mTmpFile;
    private Button buttonFront;
    private Button buttonBack;
    public ArrayList<ImageView> imageViews = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.carinfo_activity);
        ButterKnife.bind(this);
        initImageLists();
        images = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            File file = new File("1");
            images.add(i, file);
        }
    }


    private void initImageLists() {
        imageViews.add(selectIvIdcardposition);
        imageViews.add(selectIvIdcardback);
        imageViews.add(selectIvCarinfo);
        imageViews.add(selectArrmedphoto);
        imageViews.add(homeCallPolice);
        imageViews.add(homeInsurance);

    }

    public void showCamera() {
        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            mTmpFile = OtherUtils.createFile(getApplicationContext());
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
            startActivityForResult(cameraIntent, REQUEST_CAMERA);
        } else {
            Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();

        }

    }

    public void showCaptrue() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, REQUEST_ALBUM_OK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CAMERA:
                //相机返回结果
                if (mTmpFile.length() > 0) {
                    Log.d(TAG, "onActivityResult: 请求相机： " + mTmpFile.getAbsolutePath());
                    // Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(mTmpFile));
                    if (images.get(indexOf) != null) {
                        images.remove(indexOf);
                    }
                    images.add(indexOf, mTmpFile);
                    for (int i = 0; i < images.size(); i++) {

                        File file = images.get(indexOf);
                  /*  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    getBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte[] bytes=baos.toByteArray();*/
                        Glide.with(this).load(file).into(imageViews.get(indexOf));

                    }
                }
                break;
            case REQUEST_ALBUM_OK:
                //相册返回结果
                if (data == null) {
                    return;
                }
                Log.d(TAG, "onActivityResult:相册 " + data.getData().toString());
                ContentResolver resolver = getContentResolver();
                try {
                    File file = uri2File(data.getData());
                    if (images.get(indexOf) != null) {
                        images.remove(indexOf);
                    }
                    images.add(indexOf, file);
                    for (int i = 0; i < images.size(); i++) {
                        File file1 = images.get(indexOf);
                        Glide.with(this).load(file1).into(imageViews.get(indexOf));

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }

    }


    public int indexOf;

    @OnClick({R.id.select_iv_idcardposition, R.id.select_arrmedphoto,
            R.id.select_iv_idcardback, R.id.home_call_police,
            R.id.select_iv_carinfo, R.id.home_insurance,
            R.id.carinfo_bottom})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.select_iv_idcardposition:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.select_arrmedphoto:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.select_iv_idcardback:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.home_call_police:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.select_iv_carinfo:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.home_insurance:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.carinfo_bottom:
                Log.d("carifo", "123123");
                PeopleInfomation peopleInfomation = new PeopleInfomation();
                peopleInfomation.files = images;
                Intent intent = new Intent(this, ApplyLabelActivity.class);
                intent.putExtra("people", peopleInfomation);
                setResult(3, intent);
                finish();
                break;
        }

    }

    private void showPictrue() {
        if (indexOf == -1 && images.get(indexOf).length() == 0) {
            ToastUtil.getToast("请先选择图片展示", this);
            return;
        }

        llShowPictrue.setVisibility(View.VISIBLE);
        llSelectPictrue.setVisibility(View.GONE);
        button.setVisibility(View.GONE);
        for (int i = 0; i < images.size(); i++) {
            File file1 = images.get(indexOf);
            Glide.with(this).load(file1).into(ivShowPictrue);
        }
        ivShowPictrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llShowPictrue.setVisibility(View.GONE);
                llSelectPictrue.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
                ivShowPictrue.setVisibility(View.INVISIBLE);
            }
        });
    }

    public void showChooseDialog() {
        final String[] datas = new String[]{"打开相机", "打开相册", "预览"};
        AlertDialog.Builder builder = new AlertDialog.Builder(CarInfoActivity.this);  //先得到构造器
        builder.setTitle("选择照片方式"); //设置标题
        //builder.setMessage("是否确认退出?"); //设置内容
        builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
        //设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。
        builder.setItems(datas, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (which == 0) {
                    showCamera();
                } else if (which == 1) {
                    showCaptrue();
                } else {
                    showPictrue();
                }
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
                Toast.makeText(CarInfoActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }

    private File uri2File(Uri uri) {
        File file = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        int actual_image_column_index = actualimagecursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor
                .getString(actual_image_column_index);
        file = new File(img_path);
        return file;
    }

}
